package com.ys.controller.api.eKnowAi;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.eKnowAi.EKnowScene;
import com.ys.entity.eKnowAi.EKnowScenePromptKey;
import com.ys.entity.sys.YsButton;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.enume.sys.YsButtonEnum;
import com.ys.service.eKnowAi.EKnowScenePromptKeyService;
import com.ys.service.eKnowAi.EKnowSceneService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.YsButtonService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;

@Controller
@RequestMapping("/api/inter/eKnowScene")
public class ApiInterEKnowSceneController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterEKnowSceneController.class);

	@Autowired
	private EKnowScenePromptKeyService eKnowScenePromptKeyService;

	@Autowired
	private CommonApiService<EKnowScene> commonApiService;

	@Autowired
	private EKnowSceneService eKnowSceneService;

	@Autowired
	private YsButtonService ysButtonService;

	private static Long EKNOW_MENU_ID = 121L;

	/**
	 * 获取场景信息列表
	 */
	@PostMapping("/getEKnowSceneList")
	@ResponseBody
	public JSONObject getEKnowSceneList(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			List<EKnowScene> sceneList = new ArrayList<>();
			if(params!=null && params.get("sceneName")!=null && !"".equals(params.get("sceneName"))){
				sceneList = new EKnowScene().where("A.SceneName LIKE '%"+params.get("sceneName")+"%'").setOrderby("A.Sort ASC").queryList();
			}else {
				sceneList = new EKnowScene().setOrderby("A.Sort ASC").queryList();
			}
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("sceneList", sceneList);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道获取场景信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 设置查询的cond的sql设置
	 * @param cond
	 * @return
	 */
	public EKnowScene setSeachSql(EKnowScene cond){
		//排序
		cond.setOrderby("A.Sort ASC");
		return  cond;
	}


	/**
	 * 查询
	 */
	@RequiresPermissions("eKnowScene:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
								 @ModelAttribute EKnowScene cond
	){
		try {
			cond = setSeachSql(cond);
			LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
			return tableVoJA;
		}catch (Exception e){
			logger.error("查询场景信息出错：",e.getMessage(),e);
			LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
			tableVoJA.setCode(1);
			tableVoJA.setMsg("查询出错，请稍后重试！");
			return tableVoJA;
		}
	}


	/**
	 * 场景信息新增
	 */
	@PostMapping("/addEKnowScene")
	@ResponseBody
	public JSONObject addEKnowScene(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			String sceneName = params.get("sceneName").toString();//场景名称
			String sceneDescribe = params.get("sceneDescribe").toString();//描述
			String sceneKey = params.get("sceneKey").toString().trim();//场景标识
			int sort = Integer.parseInt(params.get("sort").toString());//排序
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID

			//判断场景标识是否重复
			EKnowScene keyHasSame = new EKnowScene().setSceneKey(sceneKey).queryFirst();
			if(keyHasSame!=null){
				result.put("code", EknowCodeEnum.ApiRetuenCode.CANNOT);
				return result;
			}

			//新增
			EKnowScene eKnowScene = new EKnowScene();
			eKnowScene.setSceneName(sceneName);//场景名称
			eKnowScene.setSceneDescribe(sceneDescribe);//场景描述
			eKnowScene.setSceneKey(sceneKey);//场景标识
			eKnowScene.setSort(sort);//排序
			eKnowScene.setUpdateUser(loginUserId);//修改用户id

			//以下是默认内容
			eKnowScene.setSceneTitle("逸道AI");//场景标题
			eKnowScene.setCleanIsOpen(1);//清空会话按钮是否开启（0关闭，1开启）
			eKnowScene.setCleanTxt("清空会话");//清空会话文案
			eKnowScene.setCleanPrompt("是否清空会话记录，开启新会话？");//点击清空按钮时的提示文案
			eKnowScene.setInputPrompt("请输入您要问的问题");//输入框文案
			eKnowScene.setInputMax(1000);//输入框输入字数限制（0-1000）
			eKnowScene.setKnowledgeBaseIsOpen(1);//使用知识库问答配置是否开启（0关闭，1开启）
			eKnowScene.setKnowledgeBaseIsTxt("使用知识库问答");//使用知识库问答选项的文案
			eKnowScene.setModelRoleIsOpen(1);//用户自定义AI角色名是否开启（0关闭，1开启）
			eKnowScene.setModelRoleTxt("设置AI角色名");//用户自定义AI角色名选项的文案
			eKnowScene.setModelDefaultName("逸道AI");//AI默认角色名
			eKnowScene.setHeadType(0);//头像类型（0文字加纯色背景、1图片）
			eKnowScene.setHeadColor("#16BAAA");//头像背景颜色
			eKnowScene.setHeadImagePath("https://file.mini-ease.com/upload/nomodule/202311/02/230311820.png");//头像图片链接地址
			eKnowScene.setUserChatTimes(1000);//用户每天进行问答的次数限制
			eKnowScene.setUserChatOverPrompt("不好意思，您今天的会话次数已用完。");//用户到达次数限制时的提示文案
			eKnowScene.setPrologue("您好，我是*。请问有什么可以帮您的吗？");//开场白设置
			eKnowScene.setSorryTxt("不好意思，系统出现问题了，请稍后重试！");//模型无法回答时的提示语
			eKnowScene.setPraiseTxt("点赞");//点赞按钮提示文案
			eKnowScene.setTreadTxt("点踩");//点踩按钮提示文案
			eKnowScene.setEvaluateBack("感谢您的反馈");//评价反馈文案
			eKnowScene.setMoreRecordTxt("点击加载更多...");//点击更多聊天记录文案
			eKnowScene.setNoMoreRecordTxt("暂无其他聊天记录");//无更多聊天记录文案
			eKnowScene.setEvaluateError("操作失败，请稍后重试");//评价反馈失败提示语
			eKnowScene.setIsLimitTimes(1);//是否限制用户每天对话次数（0否，1是）
			eKnowScene.setOpenIsNewChat(0);//用户每次开启是否默认开启新会话（0否，1是）
			eKnowScene.setEmbeddingBackCount(5);//向量数据库调用个数
			eKnowScene.setEmbeddingBackSource(new BigDecimal(BigInteger.ZERO));//置信度（0-1），为0时表示不设置置信度
			eKnowScene.setAiSystem("你是逸思电商制作的AI助手，名字叫*");//ai人设
			eKnowScene.setQuestionTemplateIsOpen(0);//问题模版是否开启（0否，1是）
			eKnowScene.setQuestionTemplateTxt("选择提问模版");//问题模版文案
			eKnowScene.setSelectSceneTxt("场景：");//选择场景文案
			eKnowScene.setAiModelTxt("选择AI模型");//选择Ai模型文案

			int isAdd = eKnowSceneService.add(eKnowScene);
			if(isAdd>0){
				EKnowScene eKnowSceneInfo = new EKnowScene().setSceneKey(sceneKey).queryFirst();
				if(eKnowSceneInfo!=null){
					long sceneId = eKnowSceneInfo.getId();
					//新增关联表
					EKnowScenePromptKey eKnowScenePromptKey1 = new EKnowScenePromptKey();
					eKnowScenePromptKey1.setSceneId(sceneId);
					eKnowScenePromptKey1.setKeyId(3L);
					eKnowScenePromptKeyService.add(eKnowScenePromptKey1);
					EKnowScenePromptKey eKnowScenePromptKey2 = new EKnowScenePromptKey();
					eKnowScenePromptKey2.setSceneId(sceneId);
					eKnowScenePromptKey2.setKeyId(4L);
					eKnowScenePromptKeyService.add(eKnowScenePromptKey2);
				}
				//新增按钮权限表
				ysButtonService.add(EKNOW_MENU_ID, YsButtonEnum.Type.NORMAL.value, YsButtonEnum.StyleType.BLUE.value, sort, "event-to-"+sceneKey, sceneName, "icon-add-btn", "eKnowAi:"+sceneKey);
			}
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道新增场景信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 场景信息修改
	 */
	@PostMapping("/updateEKnowScene")
	@ResponseBody
	public JSONObject updateEKnowScene(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			Long id = Long.parseLong(params.get("id").toString());//场景id
			String sceneName = params.get("sceneName").toString();//场景名称
			String sceneDescribe = params.get("sceneDescribe").toString();//描述
			String sceneKey = params.get("sceneKey").toString().trim();//场景标识
			int sort = Integer.parseInt(params.get("sort").toString());//排序
			String loginUserId = ShiroUtils.getUserId();//登录的用户ID

			//判断场景标识是否重复
			EKnowScene keyHasSame = new EKnowScene()
					.setSceneKey(sceneKey)
					.where("A.Id !="+id)
					.queryFirst();
			if(keyHasSame!=null){
				result.put("code", EknowCodeEnum.ApiRetuenCode.CANNOT);
				return result;
			}

			//旧数据
			EKnowScene eKnowSceneOld = new EKnowScene().setId(id).queryFirst();
			if(eKnowSceneOld==null){
				//无旧数据
				result.put("code", EknowCodeEnum.ApiRetuenCode.PARAMSERROR);
				return result;
			}

			//修改
			EKnowScene eKnowScene = new EKnowScene();
			eKnowScene.setId(id);
			eKnowScene.setSceneName(sceneName);//场景名称
			eKnowScene.setSceneDescribe(sceneDescribe);//场景描述
			eKnowScene.setSceneKey(sceneKey);//场景标识
			eKnowScene.setSort(sort);//排序
			eKnowScene.setUpdateUser(loginUserId);//修改用户id
			int isSave = eKnowSceneService.update(eKnowScene);
			if(isSave>0){
				String oldSceneKey = "eKnowAi:"+eKnowSceneOld.getSceneKey();
				//按钮权限相关
				YsButton ysButton = new YsButton().setNameShiroAuth(oldSceneKey).queryFirst();
				if(ysButton!=null){
					ysButtonService.edit(ysButton.getId(), null, YsButtonEnum.StyleType.BLUE.value, sceneName, "event-to-"+sceneKey, "icon-add-btn", "eKnowAi:"+sceneKey);
				}else {
					//新增按钮权限表
					ysButtonService.add(EKNOW_MENU_ID, YsButtonEnum.Type.NORMAL.value, sort, YsButtonEnum.StyleType.BLUE.value, "event-to-"+sceneKey, sceneName, "icon-add-btn", "eKnowAi:"+sceneKey);
				}
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道修改场景信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 删除
	 */
	@PostMapping("/delEKnowScene")
	@ResponseBody
	public JSONObject delEKnowScene(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			Long id = Long.parseLong(params.get("id").toString());//场景id
			//旧数据
			EKnowScene eKnowSceneOld = new EKnowScene().setId(id).queryFirst();
			if(eKnowSceneOld==null){
				//无旧数据
				result.put("code", EknowCodeEnum.ApiRetuenCode.PARAMSERROR);
				return result;
			}
			//删除场景以及场景关联表
			eKnowSceneService.del(id);

			//删除按钮权限相关
			YsButton ysButton = new YsButton().setNameShiroAuth("eKnowAi:"+eKnowSceneOld.getSceneKey()).queryFirst();
			if(ysButton!=null){
				ysButtonService.deleteTrue(ysButton.getId());
			}
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道删除场景信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 获取场景信息
	 */
	@PostMapping("/getEKnowSceneInfoById")
	@ResponseBody
	public JSONObject getEKnowSceneInfoById(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			Long id = Long.parseLong(params.get("id").toString());//场景id
			EKnowScene eKnowScene = new EKnowScene().setId(id).queryFirst();
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("eKnowScene", eKnowScene);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道获取场景信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/*
	 * 获取场景信息
	 */
	@PostMapping("/getEKnowSceneListByRole")
	@ResponseBody
	public JSONObject getEKnowSceneListByRole(HttpServletRequest request, HttpServletResponse response){
		JSONObject result = new JSONObject();
		try {
			long roleId = ShiroUtils.getRoleId();//用户角色id
			//登录的用户ID
			String loginUserId = ShiroUtils.getUserId();
			List<EKnowScene> eKnowSceneList = new ArrayList<>();
			//获取场景设置信息
			if(!loginUserId.equals("admin")){
				eKnowSceneList = new EKnowScene()
						.setOrderby("A.Sort ASC")
						.addLeftJoin("kjecp.dbo.YS_Button B ON B.NameShiroAuth = 'eKnowAi:'+A.SceneKey")
						.addLeftJoin("kjecp.dbo.YS_RoleButton R ON R.ButtonId = B.Id")
						.where("R.RoleId = "+roleId)
						.setOrderby("A.Sort ASC")
						.queryList();
			}else {
				eKnowSceneList = new EKnowScene().setOrderby("A.Sort ASC").queryList();
			}


			result.put("eKnowSceneList",eKnowSceneList);
			result.put("loginUserId",loginUserId);
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道获取场景信息出错：",e.getMessage(),e);
		}
		return result;
	}


}